import { defineStore } from 'pinia'
import router from '@/router'

export const useTabsStore = defineStore('tabs', {
  state: () => ({
    // 标签页列表
    tabList: [],
    // 当前激活的标签页
    activeTab: '',
    // 缓存的页面
    cachedViews: []
  }),

  getters: {
    /**
     * 获取标签页列表
     */
    getTabList: (state) => state.tabList,

    /**
     * 获取当前激活的标签页
     */
    getActiveTab: (state) => state.activeTab,

    /**
     * 获取缓存的页面
     */
    getCachedViews: (state) => state.cachedViews
  },

  actions: {
    /**
     * 添加标签页
     */
    addTab(tab) {
      // 如果已存在，不重复添加
      const exist = this.tabList.some(item => item.path === tab.path)
      if (!exist) {
        this.tabList.push({
          name: tab.name,
          path: tab.path,
          title: tab.title || tab.meta?.title || '未命名',
          icon: tab.meta?.icon,
          closable: tab.meta?.affix !== true
        })
      }

      // 添加到缓存
      if (tab.meta?.keepAlive && !this.cachedViews.includes(tab.name)) {
        this.cachedViews.push(tab.name)
      }

      this.activeTab = tab.path
    },

    /**
     * 删除标签页
     */
    removeTab(path) {
      const index = this.tabList.findIndex(item => item.path === path)
      if (index > -1) {
        const tab = this.tabList[index]
        this.tabList.splice(index, 1)

        // 从缓存中移除
        const cacheIndex = this.cachedViews.indexOf(tab.name)
        if (cacheIndex > -1) {
          this.cachedViews.splice(cacheIndex, 1)
        }

        // 如果删除的是当前标签页，跳转到前一个标签页
        if (this.activeTab === path) {
          const nextTab = this.tabList[index] || this.tabList[index - 1]
          if (nextTab) {
            router.push(nextTab.path)
          } else {
            router.push('/dashboard')
          }
        }
      }
    },

    /**
     * 关闭其他标签页
     */
    closeOtherTabs(path) {
      this.tabList = this.tabList.filter(item => item.path === path || !item.closable)
      this.cachedViews = []
      this.activeTab = path
    },

    /**
     * 关闭所有标签页
     */
    closeAllTabs() {
      this.tabList = this.tabList.filter(item => !item.closable)
      this.cachedViews = []
      router.push('/dashboard')
    },

    /**
     * 设置当前激活的标签页
     */
    setActiveTab(path) {
      this.activeTab = path
    },

    /**
     * 初始化固定标签页
     */
    initAffixTabs(routes) {
      const affixTabs = this.filterAffixTabs(routes)
      this.tabList = affixTabs
    },

    /**
     * 过滤出固定的标签页
     */
    filterAffixTabs(routes, basePath = '/') {
      let tabs = []
      routes.forEach(route => {
        if (route.meta?.affix) {
          const path = basePath + (route.path.startsWith('/') ? route.path.slice(1) : route.path)
          tabs.push({
            name: route.name,
            path: path,
            title: route.meta.title,
            icon: route.meta.icon,
            closable: false
          })
        }
        if (route.children) {
          const childTabs = this.filterAffixTabs(route.children, route.path + '/')
          tabs = [...tabs, ...childTabs]
        }
      })
      return tabs
    }
  },

  // 持久化
  persist: {
    key: 'VBEN_ADMIN_TABS',
    storage: sessionStorage,
    paths: ['tabList', 'activeTab']
  }
})
